package com.skyworth.web.order.service.impl;

import com.skyworth.web.admin.menu.domain.MenuModel;
import com.skyworth.web.admin.menu.repository.MenuRepository;
import com.skyworth.web.admin.store.model.StoreModel;
import com.skyworth.web.admin.store.repository.StoreRepository;
import com.skyworth.web.admin.table.repository.TableRepository;
import com.skyworth.web.order.domain.OrderModel;
import com.skyworth.web.order.repository.OrderRepository;
import com.skyworth.web.order.service.OrderService;
import com.skyworth.web.ordermenu.OrderMenuModel;
import com.skyworth.web.ordermenu.OrderMenuRepository;
import com.skyworth.web.wechat.repository.TableBindRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.skyworth.web.admin.table.model.TableModel.IDLE;
import static com.skyworth.web.admin.table.model.TableModel.USEING;
import static com.skyworth.web.ordermenu.OrderMenuModel.ORDER_ITEM_REMOVED;

/**
 * Created by skyworth on 2016/6/23.
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private StoreRepository storeRepository;

    @Autowired
    OrderRepository repository;

    @Autowired
    TableRepository tableRepository;

    @Autowired
    private OrderMenuRepository orderMenuRepository;

    @Autowired
    MenuRepository menuRepository;

    @Autowired
    private TableBindRepository tableBindRepository;

    /**
     * 为表单提供的修改和保存订单的API
     * @param orderModel
     * @return
     */
    @Override
    @Transactional
    public OrderModel saveOrUpdate(OrderModel orderModel, List<Map<String,Object>> list) {
        return save(orderModel, list);
    }

    private OrderModel save(OrderModel orderModel, List<Map<String, Object>> list) {
        if(orderModel!=null && orderModel.userId!=null && !"".equals(orderModel.userId) && orderModel.state==OrderService.ORDER_CART){
            repository.deleteOrderCart(orderModel.userId);
        }
        OrderModel model = repository.save(orderModel);
        if(orderModel.state!=OrderService.ORDER_CART) {
            tableRepository.updateTableOrderState(orderModel.tableId);
        }

        List<OrderMenuModel> insertModels = new ArrayList<>();
        for(Map<String,Object> item : list){
            OrderMenuModel insertItem = new OrderMenuModel();
            insertItem.orderId = orderModel.id;
            insertItem.menuId = Integer.parseInt(item.get("menuId").toString());
            insertItem.count = Integer.parseInt(item.get("count").toString());
            insertModels.add(insertItem);
        }

        orderMenuRepository.save(insertModels);

        return model;
    }

    /**
     * 根据订单ID查找
     * @param id
     * @return
     */
    @Override
    public OrderModel query(long id) {
        return repository.findOne(id);
    }

    @Override
    public OrderModel getLastOrder(String userId){
        return repository.getLastByUserId(userId);
    }

    @Override
    public OrderModel getLastOrder(long storeId, String userId) {
        return repository.getLastForUser(storeId,userId);
    }

    @Override
    @Transactional
    public void updateOrderState(String userId,long tableId) {
        repository.updateOrderState(userId);
        tableRepository.updateTableState(tableId);
        //tableBindRepository.unbindTable(userId);
    }

    @Override
    public OrderModel getOrderById(long id) {
        return repository.findOne(id);
    }

    @Override
    public void updateOrderCart(long tableId, String userId) {
        repository.updateOrderCart(tableId,userId);
    }

    @Override
    public void deleteOrderCart(String userId) {
        repository.deleteOrderCart(userId);
    }

    @Override
    public OrderModel getLastByTableId(long tableId) {
        return repository.getLastByTableId(tableId);
    }

    @Override
    public void removeById(long id) {
        repository.delete(id);
    }

    @Transactional
    @Override
    public Map<String, Object> getOrderForUser(long storeId, String userId, int page) {
        Map<String,Object> result = new HashMap<>();
        Pageable pageable = new PageRequest(page,15, Sort.Direction.DESC,"createdTime");
        Page<OrderModel> pageModels = repository.getOrderListByStoreIdAndUserId(storeId,userId,pageable);
        result.put("page",page);
        result.put("totalPages",pageModels.getTotalPages());
        result.put("order",pageModels.getContent());

        StoreModel storeModel = storeRepository.findOne(storeId);

        result.put("store",storeModel);

        return result;
    }

    @Override
    @Transactional
    public void refuseOrder(Long id) {
        repository.setOrderState(id,ORDER_WAITER_REFUSE);
        //台桌状态改为空闲状态
        tableRepository.setTableStateByOrderId(id,IDLE);
    }

    @Override
    @Transactional
    public void acceptOrder(Long id) {
        repository.setOrderState(id, ORDER_CONFIRMED);
        //台桌状态改为空闲状态
        tableRepository.setTableStateByOrderId(id,USEING);
    }

    /**
     * 服务员提交订单
     * @param om
     * @param foods
     */
    @Transactional
    @Override
    public OrderModel waiterCreateOrder(OrderModel om, List<Map<String, Object>> foods) {
        OrderModel orderModel = save(om,foods);
        return orderModel;
    }

    @Override
    public List<OrderModel> getOnGoingOrders(Long storeId) {

        List<OrderModel> list = repository.findOngoingOrders(storeId);
        return list;
    }

    /**
     * 用户的订单列表
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public Page<OrderModel> queryByUserId(String userId, int page, int pagesize) {
        Pageable pageable = new PageRequest(page,pagesize, Sort.Direction.DESC,"createdTime");
        return repository.queryByUserId(userId,pageable);
    }

    @Override
    public Page<OrderModel> queryByStoreId(long storeId, int page, int pagesize) {
        Pageable pageable = new PageRequest(page,pagesize,Sort.Direction.DESC,"createdTime");
        return repository.queryByStoreId(storeId,pageable);
    }

    /**
     * 用户删除订单，首先要判断订单状态
     * @param orderId
     * @return
     */
    @Override
    public OrderModel deleteByUser(long orderId) {


        return null;
    }

    /**
     * 商家删除订单，首先要判断订单状态
     * @param orderId
     * @return
     */
    @Override
    public OrderModel deleteByStore(long orderId) {
        return null;
    }



    /**
     * 服务员退菜
     * @param itemId 要删除项，在 ff_map_order_menu中的id
     * @return
     */
    @Override
    @Transactional
    public OrderModel removeMenuItem(Long itemId) {

        OrderMenuModel orderMenuModel = orderMenuRepository.findOne(itemId);
        orderMenuModel.removeFlag = ORDER_ITEM_REMOVED;
        //修改removeFlag为1，即软删除
        orderMenuModel = orderMenuRepository.save(orderMenuModel);

        //订单价格修改
        MenuModel menuModel = menuRepository.findOne(orderMenuModel.menuId);
        float price = menuModel.unitPrice * orderMenuModel.count;
        //优惠的价格--折扣价
        if(menuModel.discount != 10){
            price *= menuModel.discount * 0.1;
        }

        OrderModel orderModel = repository.findOne(orderMenuModel.orderId);
        orderModel.price -= price;
        orderModel.originalPrice -= menuModel.unitPrice;

        // 转化为保留小数点后一位
        orderModel.price = toPointOne(orderModel.price);
        orderModel.originalPrice = toPointOne(orderModel.originalPrice);
        //更新数据库
        orderModel = repository.save(orderModel);

        return orderModel;
    }

    /**
     * 转换为一位小数点的float类型
     * @param f
     * @return
     */
    private float toPointOne(float f){
        if(f == Math.floor(f)){ //小数点后面为0 ，在去掉0
            return f;
        }else{
            return Math.round(f * 10) / 10;
        }
    }
}
